package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.mapper.DeptMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.util.CommonService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 院方科室 服务实现类
 * </p>
 */
@Service
public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, Dept> implements DeptService {

    @Override
    public boolean saveOrUpdate(Dept entity) {
        boolean b = super.saveOrUpdate(entity);
        CacheUtils.put(CacheUtils.BASE_DEPT, entity.getId(), entity);
        return b;
    }

    @Override
    public Integer syncOffice() {
        Integer integer = baseMapper.syncOffice();
//        更新名称,id
        baseMapper.updateDept();
        //院方科室
        CommonService.cacheDept();
        return integer;
    }

    @Override
    public List<Dept> listByUserId(String userId, String deptId) {
        List<Dept> list = baseMapper.listByUserId(userId,deptId);
        return list;
    }

    @Override
    public Dept findByOfficeSystemCode(String officeSystemCode) {
        return this.getOne(
                Wrappers.<Dept>query().eq("office_system_code", officeSystemCode)
        );
    }


    @Override
    public Page<Map> pageForSelect(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForSelect(context.getPage(), context.getWrapper(), context.getParams(),userParam);
    }



    @Override
    public Dept getDeptByWarehouseId(String warehouseId, String WarehouseName) {
        List<Dept> deptList = this.list(Wrappers.<Dept>query().eq("warehouse_id", warehouseId));
        if (deptList != null && deptList.size() == 1) {
            return  deptList.get(0);
        }
        if (deptList != null && deptList.size() > 1) {
            throw new BusinessException("仓库【%s】找到【%s】个科室，请联系运营人员检查科室配置",WarehouseName,deptList.size());
        }
        throw new BusinessException("未找到仓库【%s】所属的科室，请联系运营人员检查科室配置",WarehouseName);
    }

    @Override
    public Dept getDeptByWarehouseId(String warehouseId) {
        List<Dept> deptList = this.list(Wrappers.<Dept>query().eq("warehouse_id", warehouseId));
        if (deptList != null && deptList.size() == 1) {
            return  deptList.get(0);
        }
        return null;
    }

}
